<template>
  <div class="min-h-screen bg-neutral-light p-6">
    <div class="max-w-md mx-auto bg-white rounded-xl shadow-lg overflow-hidden">
      <div class="p-6">
        <h1 class="text-2xl font-bold text-neutral mb-4">摄像头测试</h1>
        
        <!-- 当前协议显示 -->
        <div class="mb-6 p-4 bg-gray-100 rounded-lg">
          <p class="text-gray-700">当前访问协议: <span class="font-medium">{{ currentProtocol }}</span></p>
          <p v-if="currentProtocol === 'http:'" class="text-danger mt-2 text-sm">
            <i class="fa fa-exclamation-circle"></i> 警告: 摄像头API在HTTP环境中受限
          </p>
          <p v-else class="text-success mt-2 text-sm">
            <i class="fa fa-check-circle"></i> 已在HTTPS环境中运行
          </p>
        </div>
        
        <!-- 摄像头预览区域 -->
        <div v-if="showPreview" class="mb-6">
          <div class="aspect-video bg-black rounded-lg overflow-hidden">
            <video ref="video" autoplay playsinline class="w-full h-full object-cover"></video>
          </div>
        </div>
        
        <!-- 状态消息 -->
        <div v-if="statusMessage" class="mb-6 p-4 rounded-lg" :class="statusType === 'error' ? 'bg-danger/10 text-danger' : 'bg-success/10 text-success'">
          <p>{{ statusMessage }}</p>
        </div>
        
        <!-- 控制按钮 -->
        <div class="flex flex-col gap-3">
          <button 
            @click="requestCameraPermission"
            :disabled="isRequesting"
            class="py-3 bg-primary text-white font-medium rounded-lg hover:bg-primary/90 transition-colors"
          >
            {{ isRequesting ? '请求中...' : '请求摄像头权限' }}
          </button>
          
          <button 
            v-if="showPreview"
            @click="stopCamera"
            class="py-3 bg-white text-gray-700 font-medium rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors"
          >
            关闭摄像头
          </button>
        </div>
        
        <!-- 提示信息 -->
        <div class="mt-6 text-sm text-gray-500">
          <p class="mb-2">提示:</p>
          <ul class="list-disc list-inside space-y-1">
            <li>在开发环境中，请使用 https://localhost:5174 或 https://localhost:5175 访问</li>
            <li>首次请求可能需要在浏览器和系统中授权</li>
            <li>生产环境必须使用HTTPS</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CameraTest',
  data() {
    return {
      currentProtocol: window.location.protocol,
      showPreview: false,
      stream: null,
      isRequesting: false,
      statusMessage: '',
      statusType: '' // 'success' 或 'error'
    };
  },
  methods: {
    async requestCameraPermission() {
      if (this.isRequesting) return;
      
      this.isRequesting = true;
      this.statusMessage = '';
      
      try {
        // 检查浏览器支持
        if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
          this.showStatus('错误: 您的浏览器不支持摄像头访问功能', 'error');
          return;
        }
        
        // 检查HTTPS环境
        if (window.location.protocol !== 'https:') {
          this.showStatus('错误: 请在HTTPS环境下使用摄像头功能', 'error');
          this.isRequesting = false;
          return;
        }
        
        // 请求摄像头权限
        this.stream = await navigator.mediaDevices.getUserMedia({
          video: {
            width: { ideal: 640 },
            height: { ideal: 480 },
            facingMode: { ideal: 'environment' }
          }
        });
        
        // 设置视频流
        const video = this.$refs.video;
        video.srcObject = this.stream;
        
        this.showPreview = true;
        this.showStatus('成功: 摄像头权限已获取', 'success');
        
      } catch (error) {
        console.error('摄像头请求错误:', error);
        
        let errorMsg = '无法访问摄像头';
        switch(error.name) {
          case 'NotAllowedError':
            errorMsg = '权限被拒绝: 请在设备设置中允许使用摄像头';
            break;
          case 'NotFoundError':
            errorMsg = '未检测到可用的摄像头设备';
            break;
          case 'NotReadableError':
            errorMsg = '摄像头被其他应用占用';
            break;
          case 'OverconstrainedError':
            errorMsg = '无法满足摄像头的配置要求';
            break;
        }
        
        this.showStatus(`错误: ${errorMsg}`, 'error');
      } finally {
        this.isRequesting = false;
      }
    },
    
    stopCamera() {
      if (this.stream) {
        this.stream.getTracks().forEach(track => track.stop());
        this.stream = null;
      }
      this.showPreview = false;
      this.statusMessage = '';
    },
    
    showStatus(message, type) {
      this.statusMessage = message;
      this.statusType = type;
      
      // 5秒后自动清除成功消息
      if (type === 'success') {
        setTimeout(() => {
          this.statusMessage = '';
        }, 5000);
      }
    }
  },
  
  beforeUnmount() {
    this.stopCamera();
  }
};
</script>

<style scoped>
/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 应用动画 */
.aspect-video,
button {
  animation: fadeIn 0.3s ease-out;
}
</style>